<template>
  <el-drawer v-model="dialogVisible" :title="drawerType ? '新增抄表纪录' : '编辑抄表纪录'">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="150px"
      class="demo-ruleForm2"
    >
      <el-form-item label="抄表日期：" prop="date">
        <el-date-picker
          v-model="ruleForm.date"
          type="date"
          placeholder="请选择抄表日期"
          format="YYYY/MM/DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="抄表度数：" prop="currentData">
        <el-input type="number" v-model="ruleForm.currentData" placeholder="请输入抄表度数" />
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input v-model="ruleForm.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="文件：" v-if="drawerType">
        <el-upload
          ref="upload"
          :class="{ hide: fileList[0] }"
          :limit="1"
          action="#"
          :auto-upload="false"
          v-model:file-list="fileList"
          :on-change="beforeUpload"
          list-type="picture-card"
          style="width: 280px"
          :on-preview="handlePictureCardPreview"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
      </span>
    </template>
    <el-dialog v-model="imgDialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 720px" />
    </el-dialog>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import type { FormInstance } from 'element-plus'
  import {
    postMeterRecordCreate,
    putMeterRecordUpdate,
  } from '@/api/controller/meter-record-controller/index'
  import { ElMessage } from 'element-plus'
  const ruleFormRef = ref<FormInstance>()
  const drawerType = ref(true)
  const fileList = ref([])
  const ruleForm = ref({
    siteId: null,
    date: null,
    currentData: null,
    remark: null,
  })
  const rules = reactive({
    date: [{ required: true, message: '请选择抄表日期', trigger: 'blur' }],
    currentData: [
      { required: true, message: '请输入抄表度数', trigger: 'blur' },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: '请输入大于或等于0的数字(最多2位小数)',
      },
    ],
    remark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })
  const dialogVisible = ref(false)
  //新增或修改
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        if (drawerType.value) {
          if (fileList.value[0]) {
            const file = new FormData()
            file.append('file', fileList.value[0].raw)
            const result = await postMeterRecordCreate(ruleForm.value, file, { loading: true })
            if (result.code === 200) {
              dialogVisible.value = false
              await emit('getData')
              ElMessage.success('添加成功')
            }
          } else {
            ElMessage.warning('请上传文件')
            return false
          }
        } else {
          const result = await putMeterRecordUpdate(ruleForm.value, { loading: true })
          if (result.code === 200) {
            dialogVisible.value = false
            await emit('getData')
            ElMessage.success('修改成功')
          }
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const show = (data) => {
    if (data) {
      ruleForm.value = JSON.parse(JSON.stringify(data))
      drawerType.value = false
    } else {
      drawerType.value = true
      for (let key in ruleForm.value) {
        ruleForm.value[key] = null
      }
      ruleForm.value.siteId = history.state?.id
    }
    dialogVisible.value = true
    fileList.value = []
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }

  const dialogImageUrl = ref('')
  const imgDialogVisible = ref(false)
  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    imgDialogVisible.value = true
  }
  const beforeUpload = (file) => {
    const { name, size } = file
    //   文件类型限制
    const fileTypeFlag = /^.(jpg|jpeg|png)$/.test(
      name.substring(name.lastIndexOf('.')).toLowerCase(),
    )
    if (!fileTypeFlag) {
      ElMessage.warning('文件类型只能是.jpg .jpeg .png')
      fileList.value = []
      return false
    }
    if (size > 1024 * 1024 * 5) {
      ElMessage.warning('图片大小不能超过5MB')
      fileList.value = []
      return false
    }
  }

  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>

<style lang="scss" scoped>
  .hide {
    :deep(.el-upload--picture-card) {
      display: none !important;
    }
  }
</style>
